package com.software.myopiaparents.ui.login;


import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.software.myopiaparents.R;
import com.software.myopiaparents.base.BaseActivity;
import com.software.myopiaparents.bean.BaseInfo;
import com.software.myopiaparents.content.Constant;
import com.software.myopiaparents.http.HostType;
import com.software.myopiaparents.http.HttpApi2;
import com.software.myopiaparents.ui.AboutActivity;
import com.software.myopiaparents.ui.WebViewActivity;
import com.software.myopiaparents.utils.RegexUtils;
import com.software.myopiaparents.utils.ToastUtil;
import com.software.myopiaparents.utils.perm.NetworkUtils;
import com.umeng.analytics.MobclickAgent;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 注册页
 *
 * @author penglei
 * @date 2020/05/12
 */
public class RegisterActivity extends BaseActivity {
    private static final String TAG = "RegisterActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.tv_register_phone)
    TextView mTvRegisterPhone;
    @BindView(R.id.view_register_phone)
    View mViewRegisterPhone;
    @BindView(R.id.ll_register_phone)
    LinearLayout mLlRegisterPhone;
    @BindView(R.id.tv_register_email)
    TextView mTvRegisterEmail;
    @BindView(R.id.view_register_email)
    View mViewRegisterEmail;
    @BindView(R.id.ll_register_email)
    LinearLayout mLlRegisterEmail;
    @BindView(R.id.ll_select_register)
    LinearLayout mLlSelectRegister;
    @BindView(R.id.et_register_phone)
    EditText mEtRegisterPhone;
    @BindView(R.id.et_register_code)
    EditText mEtRegisterCode;
    @BindView(R.id.btn_register_get_code)
    Button mBtnRegisterGetCode;
    @BindView(R.id.et_register_pwd)
    EditText mEtRegisterPwd;
    @BindView(R.id.cb_dpwd1)
    CheckBox mCbDpwd1;
    @BindView(R.id.et_register_repeat_pwd)
    EditText mEtRegisterRepeatPwd;
    @BindView(R.id.cb_dpwd2)
    CheckBox mCbDpwd2;
    @BindView(R.id.cb_register_agreement)
    CheckBox mCbRegisterAgreement;
    @BindView(R.id.tv_xieyi)
    TextView mTvXieyi;
    @BindView(R.id.lay_agreement)
    LinearLayout mLayAgreement;
    @BindView(R.id.btn_register)
    Button mBtnRegister;


    private int registerType = 1; // 1:手机号码  2：邮箱
    private String account;
    private String code;
    private String pwd1;
    private String pwd2;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mTvTitleText.setText(getResources().getString(R.string.s_register));


        mCbDpwd1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mEtRegisterPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mEtRegisterPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                mEtRegisterPwd.setSelection(mEtRegisterPwd.getText().length());
            }
        });

        mCbDpwd2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mEtRegisterRepeatPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mEtRegisterRepeatPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                mEtRegisterRepeatPwd.setSelection(mEtRegisterRepeatPwd.getText().length());
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @OnClick({R.id.iv_title_left, R.id.ll_register_phone, R.id.ll_register_email, R.id.btn_register_get_code
            , R.id.btn_register, R.id.tv_xieyi})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.ll_register_phone:
                registerType = 1;
                mViewRegisterPhone.setVisibility(View.VISIBLE);
                mViewRegisterEmail.setVisibility(View.GONE);
                break;

            case R.id.ll_register_email:
                registerType = 2;
                mViewRegisterPhone.setVisibility(View.GONE);
                mViewRegisterEmail.setVisibility(View.VISIBLE);
                break;

            case R.id.btn_register_get_code:
                getCode();
                break;

            case R.id.btn_register:
                getRegister();
                break;

            case R.id.tv_xieyi:
                intent = new Intent(RegisterActivity.this, WebViewActivity.class);
                intent.putExtra("url", Constant.URL + Constant.YHXY_VIEW);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
        }
    }


    /**
     * 获取验证码
     */
    private void getCode() {
        account = mEtRegisterPhone.getText().toString().trim();
        if (registerType == 1) {
            if (TextUtils.isEmpty(account)) {
                ToastUtil.showShort(getString(R.string.toast_phone_empty));
                return;
            }
            if (!RegexUtils.checkTelephone(account)) {
                ToastUtil.showShort(getString(R.string.toast_phone_error));
                return;
            }
        } else if (registerType == 2) {
            if (TextUtils.isEmpty(account)) {
                ToastUtil.showShort(getString(R.string.toast_email_empty));
                return;
            }
            if (!RegexUtils.checkEmail(account)) {
                ToastUtil.showShort(getString(R.string.toast_email_error));
                return;
            }
        }


        if (NetworkUtils.isConnected(RegisterActivity.this)) {
            Map<String, String> params = new HashMap<>();
            params.put("account", account);
            params.put("yzm_type", 1 + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getCode(params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    startCountDown();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }

    }


    /**
     * 注册
     */
    private void getRegister() {
        account = mEtRegisterPhone.getText().toString().trim();
        code = mEtRegisterCode.getText().toString().trim();
        pwd1 = mEtRegisterPwd.getText().toString().trim();
        pwd2 = mEtRegisterRepeatPwd.getText().toString().trim();

        //验证手机号/邮箱
        if (registerType == 1) {
            if (TextUtils.isEmpty(account)) {
                ToastUtil.showShort(getString(R.string.toast_phone_empty));
                return;
            }
            if (!RegexUtils.checkTelephone(account)) {
                ToastUtil.showShort(getString(R.string.toast_phone_error));
                return;
            }
        } else if (registerType == 2) {
            if (TextUtils.isEmpty(account)) {
                ToastUtil.showShort(getString(R.string.toast_email_empty));
                return;
            }
            if (!RegexUtils.checkEmail(account)) {
                ToastUtil.showShort(getString(R.string.toast_email_error));
                return;
            }
        }

        //验证验证码
        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShort(getString(R.string.toast_verifycode_empty));
            return;
        }
        if (code.length() < 3 || code.length() > 6) {
            ToastUtil.showShort(getString(R.string.toast_verifycode_error));
            return;
        }

        //验证密码
        if (!RegexUtils.isPassword(this, pwd1)) {
            return;
        }
        if (!RegexUtils.isPassword(this, pwd2)) {
            return;
        }

        if (!pwd1.equals(pwd2)) {
            ToastUtil.showShort(getString(R.string.toast_password_two_error));
            return;
        }

        //是否同意用户协议
        if (!mCbRegisterAgreement.isChecked()) {
            ToastUtil.showShort(getString(R.string.toast_xiyi_noagreen));
            return;
        }

        if (NetworkUtils.isConnected(RegisterActivity.this)) {
            Map<String, String> params = new HashMap<>();
            params.put("account", account);
            params.put("code", code);
            params.put("password", pwd1);
            params.put("confirmPassword", pwd2);
            params.put("type", registerType+"");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getRegister(params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    MobclickAgent.onEvent(RegisterActivity.this, "register"); // 注册事件ID
                                    finish();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }


    }


    /**
     * 计时器
     */
    public void startCountDown() {
        ToastUtil.showShort(getString(R.string.toast_code_already));
        mBtnRegisterGetCode.setEnabled(false);
        mVerificationTimer.start();
    }

    /**
     * 定时器
     */
    private CountDownTimer mVerificationTimer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (mBtnRegisterGetCode != null) {
                mBtnRegisterGetCode.setEnabled(false);
                mBtnRegisterGetCode.setText(getString(R.string.toast_code_cd, millisUntilFinished / 1000));
            }
        }

        @Override
        public void onFinish() {
            if (mBtnRegisterGetCode != null) {
                mBtnRegisterGetCode.setEnabled(true);
                mBtnRegisterGetCode.setText(getString(R.string.s_register_get_code));
            }
        }
    };


}
